<template>
  <div>
    <box t1="用户管理" t2="用户列表">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryParams.query">
            <el-button slot="append" @click="getUserList" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table border="" stripe :data="userList">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 使用作用域插槽自定义列的显示内容 -->
          <!-- scope.row 就是每一行的数据 -->
          <template slot-scope="scope">
            <el-switch @change="changeUserState(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              @click="showEditDialog(scope.row.id)"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              @click="deleteUser(scope.row.id)"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                @click="ShowEditRolesBox(scope.row)"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[1, 2, 4, 10]"
        :page-size="queryParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </box>
    <!-- 新增用户弹窗页面 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="$refs.addFormRef.resetFields()"
    >
      <el-form :rules="addFormRules" :model="addForm" ref="addFormRef" label-width="70px">
        <!-- 将 Form-Item 的 prop 属性设置为需校验的字段名即可 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <!-- =================================== -->
    <!-- 修改用户弹窗页面 -->
    <!-- =================================== -->
    <el-dialog
      title="提示"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="$refs.editFormRef.resetFields()"
    >
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="70px">
        <!-- 将 Form-Item 的 prop 属性设置为需校验的字段名即可 -->
        <el-form-item label="用户名">
          <el-input :value="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectRolesId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  //  var validatePass2 = (rule, value, callback) => {
  //       if (value === '') {
  //         callback(new Error('请再次输入密码'));
  //       } else if (value !== this.ruleForm.pass) {
  //         callback(new Error('两次输入密码不一致!'));
  //       } else {
  //         callback();
  //       }
  //     };
  data() {
    var checkEmail = (rule, value, callback) => {
      // callback必须执行
      // 用户输入的内容就是value
      // value校验失败 我们执行 callback( new Error('错误提示'))
      // value校验成功 我们执行 callback()
      // 怎么去校验email 使用正则去匹配
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的邮箱格式"));
      }
    };
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的电话号码"));
      }
    };
    return {
      userList: [],
      queryParams: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      total: 0,
      userInfo: {},
      rolesList: [],
      selectRolesId: "",
      addDialogVisible: false,
      editDialogVisible: false,
      setRoleDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editForm: {},
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryParams
      });

      if (res.meta.status !== 200) {
        return this.$message.error("用户数据获取失败");
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 由组件的 size-change事件 val是用户选择的每页显示条数 由框架自动传递
    handleSizeChange(val) {
      this.queryParams.pagesize = val;
      // 改变了分页值 再重新获取用户列表数据
      this.getUserList();
    },
    // 由组件的 current-change事件 val是用户选择的每页显示条数 由框架自动传递
    handleCurrentChange(val) {
      this.queryParams.pagenum = val;
      // 改变了分页值 再重新获取用户列表数据
      this.getUserList();
    },
    add() {
      // 表单的预校验
      this.$refs.addFormRef.validate(async vali => {
        if (vali) {
          const { data: res } = await this.$http.post("users", this.addForm);
          if (res.meta.status !== 201) {
            return this.$message.error("添加用户失败");
          }
          this.$message.success("添加成功");
          // 这个属性用来控制弹窗关闭
          this.addDialogVisible = false;
          // 重新加载页面 重新获取新增之后的 用户列表
          this.getUserList();
        }
      });
    },
    async changeUserState(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );

      console.log(res);
      if (res.meta.status == 200) {
        this.$message.success("修改成功");
      } else {
        return this.$message.error("失败");
      }
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      // 因为这个后台系统可能有多个用户使用,极有可能出现多个人短时间内对同一条数据进行编辑的情况
      // 所以我们需要在打开修改对话框时 得到这条id下 对应的最新的数据
      const { data: res } = await this.$http.get("users/" + id);

      if (res.meta.status !== 200) {
        return this.$message.error("查询用户信息失败！");
      }

      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    edit() {
      // 表单的预校验是为了防止用户什么都不填直接提交
      // 其实在修改功能中没有必要做表单的预校验
      // 因为修改的表单 默认打开就已经有内容填充进去了
      this.$refs.editFormRef.validate(async vali => {
        if (vali) {
          const { data: res } = await this.$http.put(
            "users/" + this.editForm.id,
            {
              email: this.editForm.email,
              mobile: this.editForm.mobile
            }
          );
          if (res.meta.status !== 200) {
            return this.$message.error("修改失败");
          }

          // 修改成功 则 关闭修改弹窗
          this.editDialogVisible = false;
          // 重新发起请求获取最新的用户列表数据
          this.getUserList();
        }
      });
    },
    async deleteUser(id) {
      // 调用confirm弹窗
      let result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);

      if (result != "confirm") {
        return this.$message.info("用户取消删除");
      }

      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }

      // 删除成功就重新获取用户列表
      this.getUserList();
    },
    async ShowEditRolesBox(userInfo) {
      this.setRoleDialogVisible = true;
      this.userInfo = userInfo;
      // 打开需要获得角色列表
      const { data: res } = await this.$http.get("roles");
      this.rolesList = res.data;
    },
    async editRoles() {
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.selectRolesId }
      );
      if(res.meta.status !== 200){
        return this.$message.error('分配角色失败')
      }
      //成功关闭弹窗
      this.setRoleDialogVisible = false
      // 重新加载列表
      this.getUserList()
    }
  }
};
</script>

<style lang="less" scoped>
</style>